package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.User;
import com.zhentao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("zhentao-manage/yonghu")
@CrossOrigin
public class YongController {

    @Autowired
    private UserService userService;

    private static final String UPLOAD_PATH = "D:/img/image/";
    private static final String URL_PREFIX = "http://localhost:2000/";
    private static final String[] ALLOWED_IMAGE_TYPES = {".jpg", ".jpeg", ".png", ".gif"};

    /**
     * 添加用户（支持头像图片上传）
     */
    @PostMapping("/add")
    public Map<String, Object> addUser(@RequestParam("username") String username,
                                       @RequestParam("password") String password,
                                       @RequestParam(value = "phone", required = false) String phone,
                                       @RequestParam(value = "roleId", required = false) Integer roleId,
                                       @RequestParam(value = "headPic", required = false) MultipartFile headPic) {
        Map<String, Object> result = new HashMap<>();
        User user = new User();
        user.setId(UUID.randomUUID().toString());
        user.setUsername(username);
        user.setPassword(password);
        user.setPhone(phone);
        user.setRoleId(roleId != null ? roleId : 1);
        // 头像处理
        if (headPic != null && !headPic.isEmpty()) {
            String url = saveImage(headPic);
            if (url == null) {
                result.put("success", false);
                result.put("message", "头像上传失败");
                return result;
            }
            user.setHeadPic(url);
        }
        boolean success = userService.save(user);
        result.put("success", success);
        result.put("message", success ? "添加成功" : "添加失败");
        return result;
    }

    /**
     * 修改用户（支持头像图片上传）
     */
    @PostMapping("/update")
    public Map<String, Object> updateUser(@RequestParam("id") String id,
                                          @RequestParam(value = "username", required = false) String username,
                                          @RequestParam(value = "password", required = false) String password,
                                          @RequestParam(value = "phone", required = false) String phone,
                                          @RequestParam(value = "roleId", required = false) Integer roleId,
                                          @RequestParam(value = "headPic", required = false) MultipartFile headPic) {
        Map<String, Object> result = new HashMap<>();
        User user = new User();
        user.setId(id);
        if (username != null) user.setUsername(username);
        if (password != null) user.setPassword(password);
        if (phone != null) user.setPhone(phone);
        if (roleId != null) user.setRoleId(roleId);
        // 头像处理
        if (headPic != null && !headPic.isEmpty()) {
            String url = saveImage(headPic);
            if (url == null) {
                result.put("success", false);
                result.put("message", "头像上传失败");
                return result;
            }
            user.setHeadPic(url);
        }
        boolean success = userService.updateById(user);
        result.put("success", success);
        result.put("message", success ? "更新成功" : "更新失败");
        return result;
    }

    /**
     * 用户头像图片保存逻辑（返回完整URL，前缀为 http://localhost:2000/）
     */
    private String saveImage(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        boolean isAllowed = false;
        for (String type : ALLOWED_IMAGE_TYPES) {
            if (type.equals(fileSuffix)) {
                isAllowed = true;
                break;
            }
        }
        if (!isAllowed) {
            return null;
        }
        String fileName = UUID.randomUUID().toString() + fileSuffix;
        try {
            File uploadDir = new File(UPLOAD_PATH);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            File destFile = new File(UPLOAD_PATH + fileName);
            file.transferTo(destFile);
            return URL_PREFIX + fileName;
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 查看所有用户（分页，头像为图片URL）
     */
    @GetMapping("/list")
    public Page<User> list(@RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<User> page = new Page<>(pageNum, pageSize);
        Page<User> resultPage = userService.page(page);
        // 头像字段处理（如果不是完整URL则补全）
        for (User user : resultPage.getRecords()) {
            if (user.getHeadPic() != null && !user.getHeadPic().startsWith("http")) {
                user.setHeadPic(URL_PREFIX + user.getHeadPic().replace("/image/", ""));
            }
        }
        return resultPage;
    }

    /**
     * 根据条件搜索用户
     */
    @GetMapping("/search")
    public Page<User> search(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             @RequestParam(required = false) String username,
                             @RequestParam(required = false) String phone,
                             @RequestParam(required = false) Integer roleId) {
        Page<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        if (StringUtils.hasText(username)) {
            queryWrapper.like("username", username);
        }
        if (StringUtils.hasText(phone)) {
            queryWrapper.like("phone", phone);
        }
        if (roleId != null) {
            queryWrapper.eq("role_id", roleId);
        }

        return userService.page(page, queryWrapper);
    }

    /**
     * 获取用户详情（头像为图片URL）
     */
    @GetMapping("/{id}")
    public User getById(@PathVariable String id) {
        User user = userService.getById(id);
        if (user != null && user.getHeadPic() != null && !user.getHeadPic().startsWith("http")) {
            user.setHeadPic(URL_PREFIX + user.getHeadPic().replace("/image/", ""));
        }
        return user;
    }

    /**
     * 封禁用户账号（只更新role_id字段，使用UpdateWrapper）
     */
    @PostMapping("/ban/{id}")
    public Map<String, Object> banUser(@PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", id).set("role_id", -1);
            boolean success = userService.update(null, updateWrapper);
            result.put("success", success);
            result.put("message", success ? "用户已封禁" : "封禁失败");
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "操作失败：" + e.getMessage());
            return result;
        }
    }

    /**
     * 解封用户账号（只更新role_id字段，使用UpdateWrapper）
     */
    @PostMapping("/unban/{id}")
    public Map<String, Object> unbanUser(@PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", id).set("role_id", 1);
            boolean success = userService.update(null, updateWrapper);
            result.put("success", success);
            result.put("message", success ? "用户已解封" : "解封失败");
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "操作失败：" + e.getMessage());
            return result;
        }
    }

    /**
     * 审核用户实名认证资料（只更新role_id字段，使用UpdateWrapper）
     */
    @PostMapping("/audit/{id}")
    public Map<String, Object> auditUser(@PathVariable String id,
                                        @RequestParam String status,
                                        @RequestParam(required = false) String reason) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer roleId = null;
            if ("approve".equals(status)) {
                roleId = 2;
            } else if ("reject".equals(status)) {
                roleId = 3;
            }
            if (roleId == null) {
                result.put("success", false);
                result.put("message", "未知审核状态");
                return result;
            }
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", id).set("role_id", roleId);
            boolean success = userService.update(null, updateWrapper);
            result.put("success", success);
            result.put("message", success ? "审核完成" : "审核失败");
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "操作失败：" + e.getMessage());
            return result;
        }
    }

    /**
     * 获取待审核用户列表
     */
    @GetMapping("/pending-audit")
    public List<User> getPendingAuditUsers() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 假设role_id为0表示待审核状态
        queryWrapper.eq("role_id", 0);
        return userService.list(queryWrapper);
    }

    /**
     * 获取封禁用户列表
     */
    @GetMapping("/banned")
    public List<User> getBannedUsers() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // role_id为-1表示封禁状态
        queryWrapper.eq("role_id", -1);
        return userService.list(queryWrapper);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteUser(@PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = userService.removeById(id);
            result.put("success", success);
            result.put("message", success ? "删除成功" : "删除失败");
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "操作失败：" + e.getMessage());
            return result;
        }
    }
}
